package com.juguo.charginganimation.View.fragment;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.content.Context;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.juguo.charginganimation.Adapter.CardRecordAdapter;
import com.juguo.charginganimation.Base.BaseFragment;
import com.juguo.charginganimation.Bean.PhotoBean;
import com.juguo.charginganimation.Data.remote.RetrofitManager;
import com.juguo.charginganimation.R;
import com.juguo.charginganimation.utils.UITools;
import com.juguo.charginganimation.Viewmodel.PromptViewModel;
import com.juguo.charginganimation.databinding.PromptFragmentBinding;
import com.juguo.charginganimation.repository.PixabayService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.lemon.view.RefreshRecyclerView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class PromptFragment extends BaseFragment {

    private PromptViewModel mViewModel;
    private PromptFragmentBinding binding;
    private PixabayService service = RetrofitManager.getInstance().getRetrofit().create(PixabayService.class);
    private CompositeDisposable mDisposable = new CompositeDisposable();

    public static PromptFragment newInstance() {
        return new PromptFragment();
    }

    private RefreshRecyclerView mRecyclerView;
    private CardRecordAdapter mAdapter;
    private Handler mHandler;
    private int page = 1;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater,R.layout.prompt_fragment, container, false);
        return binding.getRoot();
    }

    @Override
    protected int initLayout() {
        return 0;
    }

    @Override
    protected void initView(View view) {

    }

    @Override
    protected void initData(Context mContext) {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(PromptViewModel.class);
        //修复标题栏与状态栏重叠
        UITools.fitTitleBar(getActivity(), getView());
        binding.tvTitle.setText("充电提示音");
        promPtf();
    }

    private void promPtf(){
        mHandler = new Handler();
        mAdapter = new CardRecordAdapter(getContext());
        mRecyclerView = (RefreshRecyclerView) getActivity().findViewById(R.id.recycler_view);
        mRecyclerView.setSwipeRefreshColors(0xFF437845, 0xFFE44F98, 0xFF2FAC21);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getContext(),1));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addRefreshAction(() -> getsData());

        mRecyclerView.addLoadMoreErrorAction(() -> {
            getsData();
            page++;
        });

        mRecyclerView.post(() -> {
            mRecyclerView.showSwipeRefresh();
            getsData();
        });
    }

    public void getData(final boolean isRefresh, List<PhotoBean.Photos> list) {
        mHandler.postDelayed(() -> {
            if (isRefresh) {
                page = 1;
                mAdapter.clear();
                mAdapter.addAll(list);
                mRecyclerView.dismissSwipeRefresh();
                mRecyclerView.getRecyclerView().scrollToPosition(0);
            } else if (page == 10) {
                mAdapter.showLoadMoreError();
            } else {
                mAdapter.addAll(list);
                if (page >= 20) {
                    mRecyclerView.showNoMore();
                }
            }
        }, 1000);
    }

    private void getsData() {
        Map<String, Object> map = new HashMap<>();
        map.put("order", "desc");
        map.put("sort", "add_time");
        map.put("type", 102);
        //{"param":{map}}
        Map<String, Object> param = new HashMap<>();
        param.put("param", map);
        RequestBody body = RequestBody.create(MediaType.get("application/json; charset=utf-8"), new Gson().toJson(param));
        mDisposable.add(
                service.getList(body)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<PhotoBean>() {
                            @Override
                            public void accept(PhotoBean photoBean) throws Exception {
                                //刷新的请求，用postValue()
                                //Log.d(TAG, "loadMore: " + photoBean);
                                getData(true, photoBean.getPhotolist());
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                // Log.d(TAG, "loadMore: " + throwable);
                            }
                        }));
    }
}